const app = getApp()
const { formatDate } = require('../../lib/util')
const { saveBill } = require('../../api/bill')
const { getAds, getConfig } = require('../../api/common')

const DATA_SWITCHES = [{name: '花 费'},  {name: '收 入'}]
const DATA_AD_DEFAULT = {showText: true, text: '每天进步一丢丢', showImage: false, image: ''}

Page({
  data: {
    currentIndex: 0,
    switches: DATA_SWITCHES,
    category: app.global.user.category,
    cateIndex: [0, 0],
    date: formatDate('yyyy-MM-dd'),
    ad: DATA_AD_DEFAULT,
    money: '',
    remark: '',
    editBill: null, //正在编辑的账单
    mostUsedRemarks: null,
    remarkCache: false
  },
  onLoad: function (options) {
    if (!this.data.category) {
      // 为 app 对象绑定回调
      app.userInfoReadyCallback = user => {
        this.setData({ category: user.category })
      }
    }
    
    this._init()

    this.setData({ 
      mostUsedRemarks: (wx.getStorageSync('mostUsedRemarks') || []).slice(0, 3)
    })
  },
  onShow() {
    var editBill = wx.getStorageSync('editBill')
    if (editBill) {
      wx.removeStorageSync('editBill')
      var cateIndex = this.data.cateIndex
      cateIndex[editBill.type] = editBill.categoryId
      this.setData({
        editBill: editBill,
        currentIndex: editBill.type,
        cateIndex: cateIndex,
        date: editBill.date,
        money: editBill.money,
        remark: editBill.remark
      })
    }
    var showAd = wx.getStorageSync('showImageAds')
    if (showAd && this.data.ad.showImage && this.data.ad.images.length) {
      var imageIndex = Math.floor(Math.random() * this.data.ad.images.length)
      this.setData({
        'ad.image': this.data.ad.images[imageIndex]
      })
    }
  },
  onShareAppMessage: function () {
  },
  /** 取消编辑 */
  onCancelEdit () {
    this.setData({
      editBill: false,
      money: '',
      remark: ''
    })
    wx.switchTab({
      url: '/pages/bill/bill',
    })
  },
  /** switch切换 */
  onSwitch (e) {
    this.setData({
      currentIndex: e.detail.index
    })
  },
  /** 类别切换 */
  bindCateChange(e) {
    var cateIndex = this.data.cateIndex
    cateIndex[this.data.currentIndex] = e.detail.value
    this.setData({
      cateIndex: cateIndex
    })
  },
  /** 日期切换 */
  bindDateChange (e) {
    var today = formatDate('yyyy-MM-dd')
    if (e.detail.value > today) {
      wx.showToast({
        icon: 'none',
        title: '日期大于今天，不要弄错了噢~',
      })
    }
    console.log(e.detail.value)
    this.setData({
      date: e.detail.value
    })
  },
  /** 关闭广告 */
  closeAD() {
    wx.setStorageSync('showImageAds', false)
    this.setData({
      'ad.showImage': false
    })
  },
  onTapMostUse(e) {
    let now = +Date.now()
    let prev = this.prevTapTime || 0
    if (now - prev < 300) {
      this.setData({
        remark: e.target.dataset.text
      })
    }
    this.prevTapTime = now
  },
  clearMostUsed() {
    let now = +Date.now()
    let prev = this.prevTapTime || 0
    if (now - prev < 300) {
      this.setData({mostUsedRemarks: null})
      wx.removeStorage({ key: 'mostUsedRemarks' })
    }
    this.prevTapTime = now
  },
  /** 表单提交 */
  formSubmit(e) {
    var bill = e.detail.value
    if (bill.money === '') {
      wx.showToast({
        icon: 'none',
        title: '请输入金额'
      })
      return
    }
    bill.money = parseFloat(bill.money || 0)
    if (isNaN(bill.money) || bill.money < 0) {
      wx.showToast({
        icon: 'none',
        title: '请正确填写金额'
      })
      return
    }
    if (this.data.editBill) {
      bill._id = this.data.editBill._id
    }
    bill.money = +bill.money.toFixed(2)
    bill.categoryId = bill.category
    bill.category = this.data.category[this.data.currentIndex][bill.category]
    bill.date = bill.date
    bill.addtime = +new Date() / 1000 | 0
    bill.type = this.data.currentIndex

    if (!this.data.editBill) {
      // 清空
      wx.removeStorageSync('bills')
      wx.removeStorageSync('total')
    }
    wx.removeStorageSync('stat_pie')
    wx.removeStorageSync('stat_com')
    wx.removeStorageSync('filter')

    saveBill(bill).then(res => {
      if (res._id) {
        bill._id = res._id
      }
      this._handleMostUsedRemark(bill.remark)
      // 更新本地缓存数据
      this._update(bill, () => {
        this.setData({
          money: '',
          remark: '',
          editBill: false
        })
        wx.switchTab({
          url: '/pages/bill/bill',
        })
      })
    })
  },
  _handleMostUsedRemark(remark) {
    if (!remark) return
    let remarks = wx.getStorageSync('mostUsedRemarks') || []
    let data = remarks.find(a=>a.name == remark)
    if (data) {
      data.count++
    } else {
      remarks.push({name: remark, count: 1, time: +Date.now()})
    }
    remarks.sort((a, b) => {
      if (b.count == a.count) {
        return b.time - a.time
      }
      return b.count-a.count
    })
    remarks = remarks.slice(0, 10)
    wx.setStorageSync('mostUsedRemarks', remarks)
    this.setData({
      mostUsedRemarks: remarks.slice(0, 3)
    })
  },
  _update(newBill, cb) {
    var editBill = this.data.editBill
    if (editBill) {
      // 修改账单
      var bills = wx.getStorageSync('bills')
      if (bills) {
        var index = bills.data.findIndex(item => {
          return editBill._id === item._id
        })
        bills.data[index] = newBill
        wx.setStorageSync('bills', bills)
      }
      // 修改金额
      var total = wx.getStorageSync('total')
      // 判断是否存在缓存
      if (total) {
        // 判断时间范围
        if (newBill.date >= bills.begin && newBill.date <= bills.end) {
          // 判断收支类型
          if (editBill.type === newBill.type) {
            total.data[editBill.type]['money'] = +(total.data[editBill.type]['money'] - editBill.money + newBill.money).toFixed(2)
          } else {
            total.data[editBill.type]['money'] = +(total.data[editBill.type]['money'] - editBill.money).toFixed(2)
            total.data[newBill.type]['money'] = +(total.data[newBill.type]['money'] + editBill.money).toFixed(2)
          }
        } else {
          total.data[editBill.type]['money'] = +(total.data[editBill.type]['money'] - editBill.money).toFixed(2)
          total.data[editBill.type]['times'] = +(total.data[editBill.type]['times'] - 1).toFixed(2)
        }
        total.data[2]['money'] = +(total.data[1]['money'] - total.data[0]['money']).toFixed(2)
        wx.setStorageSync('total', total)
      }
      typeof cb === 'function' && cb()
    } else {
      this.setData({
        money: '',
        remark: '',
        editBill: null
      })
    }
  },
  /** 获取广告内容 */
  _init() {
    getAds().then(adData => {
      adData.image = ''
      if (adData.images.length) {
        var showImage = wx.getStorageSync('showImageAds')
        adData.showImage = showImage && adData.showImage
        var imageIndex = Math.floor(Math.random() * adData.images.length)
        adData.image = adData.images[imageIndex] //随机一张图片
      }
      this.setData({ ad: adData })
    })
    getConfig().then(res => {
      this.setData({ remarkCache: (res || {}).remarkCache || false })
    })
  }
})
